package com.fingard.dsp.bank.directbank.chinaums01;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IJSAPIOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.*;
import com.fingard.text.StringHelper;
import com.fingard.text.XmlHelper;

import java.util.Date;

public class ChinaUMS01JSAPIOrder extends ChinaUMS01Base implements IJSAPIOrder {
    @Override
    public RetAtsUnifiedOrder submitJSAPIOrder(ReqUnifiedOrder p_req) {
        RetAtsUnifiedOrder retAts = new RetAtsUnifiedOrder();
        if ("ALIPAYJSAPI01".equals(p_req.reqHeader.commandCode)) {
            return submitALIPAYJSAPIOrder(p_req);
        } else if ("WXJSAPI01".equals(p_req.reqHeader.commandCode)) {
            return submitWXJSAPIOrder(p_req);
        }
        return retAts;
    }

    @Override
    public RetAtsQueryOrder queryJSAPIPay(ReqQueryOrder p_req) {
        RetAtsQueryOrder retAts = new RetAtsQueryOrder();
        retAts.rdSeq = p_req.rdSeq;

        try {
            ActSetItem actItem = this.getBankConfig().getActSetItem(p_req.ownAct, "unifiedorder");
            if (actItem != null) {
                JSONObject queryJSAPI = new JSONObject();
                queryJSAPI.put("requestTimestamp", Format.DateTimeFormat.format(new Date()));
                queryJSAPI.put("mid", actItem.merchantId);
                queryJSAPI.put("merOrderId", p_req.rdSeq);
                queryJSAPI.put("tid", getBankConfig().getValueAsString("terminalNum"));
                queryJSAPI.put("instMid", "YUEDANDEFAULT");

                String tmpStrRet = querySend(bankFront.getUrl("queryJSAPIPay"), JSON.toJSONString(queryJSAPI), actItem);
                if (StringHelper.hasAnyChar(tmpStrRet)) {
                    if (tmpStrRet.contains("{")) {
                        JSONObject tmpJsonResp = JSON.parseObject(tmpStrRet);
                        retAts.respCode = "0";
                        retAts.respInfo = tmpJsonResp.getString("errMsg");
                        String status = tmpJsonResp.getString("status");
                        if(status!= null){
                            retAts.transState = status;
                            retAts.payInfoCode = tmpJsonResp.getString("errCode");
                            retAts.outTransID = tmpJsonResp.getString("targetOrderId");
                            retAts.oppAct = tmpJsonResp.getString("bankCardNo");
                            retAts.oppBank = tmpJsonResp.getString("bankInfo");
                        }else{
                            retAts.transState = tmpJsonResp.getString("errCode");
                            retAts.payInfoCode = tmpJsonResp.getString("errCode");
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = "银联响应数据格式非法";
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "银联响应为空";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respCode = "未找到账号[" + p_req.ownAct + "]商户配置信息!";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        return retAts;
    }

    @Override
    public RetAtsGenGetUserCodeURL GenGetUserCodeURL(ReqGenGetUserCodeURL p_req) {
        return null;
    }

    @Override
    public RetAtsGenRealNameURL genRealNameURL(ReqGenRealNameURL p_req) {
        return null;
    }

    @Override
    public RetAtsGenGetUserCodeURL getUserId(ReqGenGetUserCodeURL p_req) {
        return null;
    }

    public RetAtsUnifiedOrder submitALIPAYJSAPIOrder (ReqUnifiedOrder p_req) {
        RetAtsUnifiedOrder retAts = new RetAtsUnifiedOrder();
        retAts.rdSeq = p_req.rdSeq;

        try {
            ActSetItem actItem = getBankConfig().getActSetItem(p_req.ownAct, "unifiedorder");
            if (actItem != null) {
                JSONObject submitJSAPI = new JSONObject();
                submitJSAPI.put("requestTimestamp", Format.DateTime14Format.format(new Date()));

                String srcReserve = "";
                if ("1".equals(p_req.realNameFlag) && "0".equals(p_req.realNameType)) {
                    JSONObject srcReserveJson = new JSONObject();
                    srcReserveJson.put("payNo", p_req.rdSeq);
                    srcReserveJson.put("authFlag", "TRUE");
                    srcReserveJson.put("authMode", "CIITC");
                    srcReserveJson.put("authTransId", p_req.paymentNo);
                    srcReserveJson.put("merInstId", actItem.inMerchantId);
                    srcReserveJson.put("version", "1.0");
                    srcReserve = JSON.toJSONString(srcReserveJson);
                    submitJSAPI.put("srcReserve", srcReserve);
                }

                submitJSAPI.put("merOrderId", p_req.rdSeq);
                submitJSAPI.put("mid", actItem.merchantId);
                submitJSAPI.put("tid", actItem.termId);
                submitJSAPI.put("instMid", "YUEDANDEFAULT");

                JSONObject goodsObj = new JSONObject();
                goodsObj.put("goodsName", XmlHelper.encode(p_req.description));
                goodsObj.put("body", XmlHelper.encode(p_req.attach));
                JSONArray goodsArray = new JSONArray();
                goodsArray.add(goodsObj);
                submitJSAPI.put("goods", JSON.toJSON(goodsArray));

                submitJSAPI.put("attachedData", XmlHelper.encode(p_req.attach));
                submitJSAPI.put("orderDesc", XmlHelper.encode(p_req.description));
                submitJSAPI.put("totalAmount", StringHelper.amountMultiply100(p_req.amount));
                submitJSAPI.put("notifyUrl", actItem.notifyURL);
                submitJSAPI.put("tradeType", "JSAPI");
                submitJSAPI.put("userId", p_req.userId);

                boolean limitPay = getBankConfig().getValueAsBool("limitPay");
                submitJSAPI.put("limitCreditCard", limitPay+"");

                String tmpStrRet = querySend(bankFront.getUrl("submitJSAPIOrder"), JSON.toJSONString(submitJSAPI), actItem);
                if (StringHelper.hasAnyChar(tmpStrRet)) {
                    if (tmpStrRet.contains("{")) {
                        JSONObject tmpJsonResp = JSON.parseObject(tmpStrRet);
                        retAts.respCode = "0";
                        retAts.respInfo = tmpJsonResp.getString("errMsg");
                        String status = tmpJsonResp.getString("status");
                        if(status!= null){
                            retAts.transState = status;
                            String jsPayRequests = tmpJsonResp.getString("jsPayRequest");
                            JSONObject jsPayRequest = JSON.parseObject(jsPayRequests);
                            retAts.payInfo = jsPayRequest.getString("orderNo");
                            retAts.payInfoCode = tmpJsonResp.getString("errCode");
                            retAts.outTransID = tmpJsonResp.getString("targetOrderId");
                        }else{
                            retAts.transState = tmpJsonResp.getString("errCode");
                            retAts.payInfoCode = tmpJsonResp.getString("errCode");
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = "银联响应数据格式非法";
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "银联响应为空";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "未找到账号[" + p_req.ownAct + "]商户配置信息!";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        return retAts;
    }

    private RetAtsUnifiedOrder submitWXJSAPIOrder(ReqUnifiedOrder p_req) {
        return null;
    }

}
